<template>
  <view class="purchase-container">
    <!-- 头部信息 -->
    <view class="header-info">
      <view class="form-group">
        <text class="label">采购日期</text>
        <view class="date-picker-wrapper">
          <uni-datetime-picker
              v-model="purchaseDate"
              type="date"
              :default-date="purchaseDate"
              @change="onPurchaseDateChange"
          ></uni-datetime-picker>
        </view>
      </view>
    </view>

    <!-- 已选商品列表 -->
    <view class="selected-products">
      <view class="section-title">已选商品</view>

      <view class="empty-list" v-if="selectedProducts.length === 0">
        <text>暂无选择的商品</text>
      </view>

      <!-- 优化后的商品列表 -->
      <view class="product-item" v-for="(item, index) in selectedProducts" :key="item.productId">

        <view class="product-info">
          <!-- 商品图片和名称 -->
          <view class="product-basic-info">
            <view class="product-image">
              <image
                  :src="item.imageUrl || 'https://picsum.photos/200/200?random=' + item.productId"
                  mode="aspectFill"
                  class="product-img"
              ></image>
            </view>
            <text class="product-name">{{ item.productName || '未命名商品' }}</text>
          </view>

          <!-- 价格信息 -->
          <view class="product-price-info">
            <view class="price-row">
              <view class="price-item">
                <text class="price-label">采购价:</text>
                <view class="price-input-wrapper">
                  <input
                      type="digit"
                      v-model="item.purchasePrice"
                      placeholder="输入采购价"
                      @blur="onPriceBlur(item, 'purchase')"
                      @confirm="onPriceConfirm(item, 'purchase')"
                  />
                  <text class="price-unit">元</text>
                </view>
              </view>
              <view class="price-item">
                <text class="total-label">采购总额:</text>
                <text class="total-value">¥{{ (parseFloat(item.purchasePrice) * item.quantity).toFixed(2) }}</text>
              </view>
            </view>

            <view class="price-row">
              <view class="price-item">
                <text class="price-label">销售价:</text>
                <view class="price-input-wrapper">
                  <input
                      type="digit"
                      v-model="item.sellingPrice"
                      placeholder="输入销售价"
                      @blur="onPriceBlur(item, 'selling')"
                      @confirm="onPriceConfirm(item, 'selling')"
                  />
                  <text class="price-unit">元</text>
                </view>
              </view>
<!--              <view class="price-item">-->
<!--                <text class="total-label">销售总额:</text>-->
<!--                <text class="total-value">¥{{ (parseFloat(item.sellingPrice) * item.quantity).toFixed(2) }}</text>-->
<!--              </view>-->
              <view class="price-item" v-if="item.purchasePrice && item.sellingPrice">
                <text class="total-label">利润:</text>
                <text class="total-value">¥{{ ((parseFloat(item.sellingPrice) - parseFloat(item.purchasePrice)) * item.quantity).toFixed(2) }}</text>
              </view>
            </view>

            <!-- 数量和操作 -->
            <view class="product-actions">

              <uni-number-box
                  v-model="item.quantity"
                  :min="1"
                  :max="999"
                  @change="onQuantityChange(item, $event)"
                  class="number-box"
              ></uni-number-box>
              <view class="delete-btn" @click="removeProduct(index)">
                <uni-icons type="trash" size="28"></uni-icons>
              </view>
            </view>

          </view>
        </view>



      </view>
    </view>

    <!-- 添加商品按钮 -->
    <view class="add-product-btn" @click="openProductSelector">
      <uni-icons type="plusempty" size="32"></uni-icons>
      <text>添加商品</text>
    </view>

    <!-- 底部统计信息 -->
    <view class="summary">
      <view class="summary-item">
        <text>商品总数</text>
        <text class="total-value">{{ totalQuantity }}</text>
      </view>
      <view class="summary-item">
        <text>采购总金额</text>
        <text class="total-value">¥{{ totalPurchaseAmount.toFixed(2) }}</text>
      </view>
      <view class="summary-item">
        <text>销售总金额</text>
        <text class="total-value">¥{{ totalSellingAmount.toFixed(2) }}</text>
      </view>
      <view class="summary-item">
        <text>预计总利润</text>
        <text class="total-value profit">{{ totalProfit.toFixed(2) }}</text>
      </view>
    </view>

    <!-- 提交按钮 -->
    <view class="submit-btn" @click="submitPurchase">
      <text>提交采购单</text>
    </view>

    <!-- 商品选择器模态框 -->
    <view class="modal" v-if="showProductSelector">
      <view class="modal-mask" @click="closeProductSelector"></view>
      <view class="modal-content">
        <view class="modal-header">
          <text class="title">选择商品</text>
          <view class="close-btn" @click="closeProductSelector">
            <uni-icons type="closeempty" size="30"></uni-icons>
          </view>
        </view>
        <view class="modal-body">
          <ProductSelector
              :selectedIds="selectedProductIds"
              @select="onProductSelect"
          ></ProductSelector>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import ProductSelector from '@/components/product/ProductSelector.vue';

export default {
  components: {
    ProductSelector
  },
  data() {
    return {
      purchaseDate: '',
      selectedProducts: [],
      showProductSelector: false,
      purchaseFrom: {}
    }
  },
  onLoad() {
    this.purchaseDate = this.$dateUtils.getLocalDate();
  },
  computed: {
    selectedProductIds() {
      return this.selectedProducts.map(item => item.productId);
    },
    totalQuantity() {
      return this.selectedProducts.reduce((sum, item) => sum + (item.quantity || 0), 0);
    },
    totalPurchaseAmount() {
      return this.selectedProducts.reduce((sum, item) => sum + (item.quantity || 0) * (parseFloat(item.purchasePrice) || 0), 0);
    },
    totalSellingAmount() {
      return this.selectedProducts.reduce((sum, item) => sum + (item.quantity || 0) * (parseFloat(item.sellingPrice) || 0), 0);
    },
    totalProfit() {
      return this.totalSellingAmount - this.totalPurchaseAmount;
    }
  },
  methods: {
    openProductSelector() {
      this.showProductSelector = true;
    },
    closeProductSelector() {
      this.showProductSelector = false;
    },
    onProductSelect(product) {
      const isProductExists = this.selectedProducts.some(
          item => item.productId === product.productId
      );

      if (isProductExists) {
        uni.showToast({
          title: '此商品已添加',
          icon: 'none',
          duration: 1500
        });
        return;
      }

      // 添加默认值，同时包含采购价格、销售价格和图片
      const newProduct = {
        ...product,
        quantity: 1,
        purchasePrice: product.defaultPurchasePrice || 0,
        sellingPrice: product.defaultSellingPrice || 0,
        imageUrl: product.imageUrl // 确保商品对象包含imageUrl字段
      };

      this.selectedProducts.push(newProduct);
      this.showProductSelector = false;

      uni.showToast({
        title: '已添加商品',
        icon: 'success',
        duration: 1500
      });
    },
    removeProduct(index) {
      this.selectedProducts.splice(index, 1);
    },
    onQuantityChange(product, value) {
      // 直接使用value参数，而不是通过event.mp.detail.value
      const quantity = parseInt(value) || 1;
      const productIndex = this.selectedProducts.findIndex(
          item => item.productId === product.productId
      );

      if (productIndex !== -1) {
        this.selectedProducts[productIndex].quantity = quantity;
      }
    },
    onPriceBlur(product, type) {
      // 失去焦点时格式化价格
      const price = parseFloat(product[type + 'Price']);
      if (isNaN(price)) {
        product[type + 'Price'] = 0;
      } else {
        product[type + 'Price'] = price.toFixed(2);
      }
    },
    onPriceConfirm(product, type) {
      // 确认输入时格式化价格并验证
      const price = parseFloat(product[type + 'Price']);
      if (isNaN(price) || price <= 0) {
        uni.showToast({
          title: `请输入有效的${type === 'purchase' ? '采购' : '销售'}价格`,
          icon: 'none'
        });
        product[type + 'Price'] = 0;
      } else {
        product[type + 'Price'] = price.toFixed(2);
      }

      // 检查销售价格是否低于采购价格
      if (type === 'selling' &&
          parseFloat(product.sellingPrice) < parseFloat(product.purchasePrice)) {
        uni.showToast({
          title: '销售价格不应低于采购价格',
          icon: 'none'
        });
      }
    },
    onPurchaseDateChange(e) {
      this.purchaseDate = e.mp.detail.value;
    },
    submitPurchase() {
      if (!this.selectedProducts.length) {
        uni.showToast({
          title: '请选择商品',
          icon: 'none'
        });
        return;
      }

      // 检查所有商品价格是否有效
      const invalidProduct = this.selectedProducts.find(
          item => isNaN(parseFloat(item.purchasePrice)) ||
              parseFloat(item.purchasePrice) <= 0 ||
              isNaN(parseFloat(item.sellingPrice)) ||
              parseFloat(item.sellingPrice) <= 0
      );

      if (invalidProduct) {
        uni.showToast({
          title: '请输入有效的商品价格',
          icon: 'none'
        });
        return;
      }

      // 检查是否有销售价格低于采购价格的商品
      const unprofitableProduct = this.selectedProducts.find(
          item => parseFloat(item.sellingPrice) < parseFloat(item.purchasePrice)
      );

      if (unprofitableProduct) {
        uni.showToast({
          title: '存在销售价格低于采购价格的商品',
          icon: 'none'
        });
        return;
      }

      if (!this.purchaseDate) {
        uni.showToast({
          title: '请选择采购日期',
          icon: 'none'
        });
        return;
      }

      uni.showLoading({
        title: '提交中...',
        mask: true
      });

      this.purchaseFrom = {
        orderDate: this.purchaseDate,
        orderItems: this.selectedProducts,
        userId: this.$store.state.user.id
      };

      this.req({
        url: '/purchase/createOrder',
        method: 'POST',
        data: this.purchaseFrom
      })
          .then(res => {
            uni.hideLoading();

            if (res.code === 200) {
              uni.showToast({
                title: '提交成功',
                icon: 'success',
                duration: 2000
              });

              // 提交成功后返回上一页或跳转到订单列表
              setTimeout(() => {
                uni.navigateBack();
              }, 2000);
            } else {
              uni.showToast({
                title: res.message || '提交失败',
                icon: 'none'
              });
            }
          })
          .catch(error => {
            uni.hideLoading();
            console.error('提交采购单失败:', error);
            uni.showToast({
              title: '网络错误，请稍后再试',
              icon: 'none'
            });
          });
    }
  }
}
</script>

<style>
.product-info{
  display: flex;
}
.purchase-container {
  min-height: 100vh;
  background-color: #f8f8f8;
}

.header-info {
  background-color: #fff;
  padding: 20rpx;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
}

.form-group {
  display: flex;
  align-items: center;
  padding: 15rpx 0;
}

.label {
  width: 200rpx;
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.date-picker-wrapper {
  flex: 1;
}

/* 商品列表样式优化 */
.selected-products {
  background-color: #fff;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
  overflow: hidden;
}

.section-title {
  padding: 20rpx 25rpx;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  border-bottom: 1rpx solid #eee;
}

.empty-list {
  text-align: center;
  padding: 80rpx 0;
  color: #999;
  font-size: 28rpx;
}

.product-item {
  display: flex;
  padding: 25rpx;
  border-bottom: 1rpx solid #f5f5f5;
  flex-direction: column;
}

.product-basic-info-and-price {
  display: flex;
  margin-bottom: 15rpx;
}

.product-basic-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 20rpx;
  width: 180rpx;
  flex-shrink: 0;
}

.product-image {
  width: 180rpx;
  height: 180rpx;
  margin-bottom: 10rpx;
  border-radius: 8rpx;
  overflow: hidden;
  background-color: #f5f5f5;
}

.product-img {
  width: 100%;
  height: 100%;
}

.product-name {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 100%;
  text-align: center;
}

.product-price-info {
  flex: 1;
}

.price-row {
  display: flex;
  padding: 8rpx 0;
  align-items: center;
}

.price-item {
  display: flex;
  align-items: center;
  flex: 1;
  //width: 85rpx;
}

.price-label {
  font-size: 26rpx;
  color: #666;
  margin-right: 10rpx;
  //width: 85rpx;
}

.price-input-wrapper {
  display: flex;
  align-items: center;
  border: 1rpx solid #ddd;
  border-radius: 6rpx;
  padding: 8rpx 12rpx;
  background-color: #f9f9f9;
  flex: 1;
  max-width: 200rpx;
}

.price-input-wrapper input {
  flex: 1;
  font-size: 26rpx;
  min-width: 120rpx;
  max-width: 180rpx;
  text-align: right;
  background-color: transparent;
}

.price-unit {
  font-size: 26rpx;
  color: #666;
  margin-left: 5rpx;
}

.total-label {
  font-size: 26rpx;
  color: #333;
  margin-right: 10rpx;
  //width: 100rpx;
  text-align: right;
}

.total-value {
  font-size: 26rpx;
  font-weight: 500;
  color: #e54d42;
}

.profit-row {
  display: flex;
  padding: 8rpx 0;
  align-items: center;
}

.profit-label {
  font-size: 26rpx;
  color: #333;
  margin-right: 10rpx;
  width: 80rpx;
}

.profit-value {
  font-size: 26rpx;
  font-weight: 500;
  color: #00b42a;
}

.product-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 15rpx;
  //border-top: 1rpx dashed #eee;
}

.number-box {
  width: 200rpx;
}

.delete-btn {
  color: #999;
  padding: 10rpx;
}

.delete-btn uni-icons {
  font-size: 28rpx;
}

.add-product-btn {
  background-color: #fff;
  padding: 25rpx 0;
  text-align: center;
  font-size: 32rpx;
  color: #007aff;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
}

.add-product-btn uni-icons {
  margin-right: 10rpx;
}

/* 统计信息样式优化 */
.summary {
  display: flex;
  background-color: #fff;
  padding: 30rpx 0;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
  flex-wrap: wrap;
}

.summary-item {
  width: 50%;
  text-align: center;
  margin-bottom: 20rpx;
}

.summary-item text:first-child {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 10rpx;
}

.total-value {
  font-size: 36rpx;
  font-weight: bold;
}

.total-value:first-child {
  color: #007aff;
}

.total-value:last-child {
  color: #e54d42;
}

.profit {
  color: #00b42a;
}

/* 提交按钮样式优化 */
.submit-btn {
  background-color: #007aff;
  color: #fff;
  text-align: center;
  padding: 32rpx 0;
  font-size: 36rpx;
  border-radius: 10rpx;
  margin: 0 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,122,255,0.2);
}

/* 模态框样式优化 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
}

.modal-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  height: 80%;
  border-radius: 20rpx 20rpx 0 0;
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 25rpx 30rpx;
  border-bottom: 1rpx solid #eee;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  padding: 10rpx;
}
</style>